<template>
  <div class="update_wxkf_customer">
    <el-form ref="formData" :rules="rules" :model="form" label-width="80px" >
      <el-form-item :label="$t('configLazyLoad.channel.custAccount')" props="name">
        <el-input v-model.trim="form.name" :placeholder="$t('configLazyLoad.channel.WXOfficial008')" :maxlength=16></el-input>
        <el-tooltip class="example_tip" effect="dark" placement="bottom">
          <img slot="content" src="./img/wxkfExample.png" alt="" style="max-width: 20em"/>
          <span class="welcomeTip">{{$t('configLazyLoad.process.processLabel59')}}</span>
        </el-tooltip>
      </el-form-item>
      <el-form-item :label="$t('userInfo.avatar')" props="avatar">
        <div class="wrap_logo">
          <span class="icon_grey" v-if="!form.avatar"></span>
          <img v-else :src="form.avatar" alt="" class="icon_grey fl">
        </div>
        <div class="uploadBtn" id="uploadWXCustomerLogo">{{$t('configLazyLoad.channel.uplopadImage')}}</div>
        <p class="desc">{{$t('configLazyLoad.channel.webStyleTip7')}}</p>
      </el-form-item>
      <div style="margin: 20px">
        <!-- <el-button v-if="form.open_kfid" class="primary_btn delete_btn" style="margin-right: 20px" @click="deleteFun">{{$t('public.delete')}}</el-button> -->
        <el-button type="primary" class="primary_btn" @click="submit">{{$t('public.confirm')}}</el-button>
      </div>
    </el-form>
  </div>
</template>
<script>
import { deepClone, getCurrentDate } from '@/utils/m7Utils.js'
import {uploadTo7moorlogoImgDomain} from '@/utils/qiniuUtils'
import * as uuid from 'uuid'
export default {
  name: "updateWXCustomer",
  data () {
    return {
      current: '',
      form: {
        name: '',
        avatar: ''
      },
      oldData: {},
      rules: {
        name: [
          { required: true, message: this.$t('webchat.placeSkillsGrouop'), trigger: 'change' }
        ]
      },
      m7uploaders: []
    }
  },
  props: {
    data: {
      type: Object,
      default: {
        name: '',
        avatar: ''
      }
    },
    list: {
      type: Array,
      default: ()=>[]
    },
    corpid: String
  },
  methods: {
    update(data){
      this.form = deepClone(data)
    },
    submit () {
      let type = 'add'
      if (!this.form.name) {
        this.$message.error(this.$t('configLazyLoad.channel.WXOfficial009'))
        return
      }
      if (!this.form.avatar) {
        this.$message.error(this.$t('configLazyLoad.channel.WXOfficial010'))
        return
      }
      var action = "addWxkfAccount"
      var dataNew = {
        corpid: this.corpid,
        openKfid: this.data.open_kfid
      }
      if (this.form.open_kfid) {
        type = 'edit'
        action = "updateWxkfAccount"
        if (this.form.name === this.oldData.name && this.form.avatar === this.oldData.avatar) {
          // 数据没发生变化，不做提交操作
          this.$emit('back')
          return
        }
        if (this.form.name !== this.oldData.name) {
          this.$set(dataNew, 'name', this.form.name)
        }
        if (this.form.avatar !== this.oldData.avatar) {
          this.$set(dataNew, 'avatar', this.form.avatar)
        }
      } else {
        type = 'add'
        this.$set(dataNew, 'name', this.form.name)
        this.$set(dataNew, 'avatar', this.form.avatar)
      }
      let sendData = {}
      sendData.corpid = this.corpid
      sendData.open_kfid = this.data.open_kfid
      sendData.name = this.form.name
      sendData.avatar = this.form.avatar
      let nameArr = []
      if(this.list && this.list.length > 0) {
        this.list.forEach(item=>{
          nameArr.push(item.name)
        })
      }
      if(nameArr.includes(dataNew.name)){
        this.$message.error('名称重复，请重新填写')
      } else{
        this.$store.dispatch(action, dataNew).then((res) => {
          if (res && res.success) {
            this.$message.success(this.$t('config.channel.saveSuccess'))
            // this.refresh()
            this.$emit('back',sendData,type)
          } else {
            // this.$message.error(this.$t('config.channel.saveError'))
          }
        })
      }
    },
    initUpload () {
      let account = this.$store.state.session.user.account
      let self = this
      let fileAdded = function (up, files) {
        console.log('fileAdd')
      }
      let beforeUploadSysLogo = function (up, file) {
        // self.systemMsgLogoUi.show = true
        // self.systemMsgLogoUi.percent = 0
        console.log('beforeUpload1')
      }
      let upProgressSysLogo = function (up, file) {
        // self.systemMsgLogoUi.percent = file.percent
        console.log('uploadSystem')
      }
      let upCompleteSysLogo = function (up, file) {
        // self.systemMsgLogoUi.show = false
        console.log('uploadCompleteSystem')
      }
      let systemLogouploaded = function (up, file, info) {
        let domain = up.getOption('domain')
        let res = JSON.parse(info||'{}')
        let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
        console.log(sourceLink,'sourceLink')
        if (!sourceLink) {
          return
        }
        self.$set(self.form,'avatar',sourceLink)
        // self.form.avatar = sourceLink
        self.$message.success(self.$t('configLazyLoad.channel.uploadSucc'))
      }
      let error = function (up, err, errTip) {
        if (errTip) {
          self.$message.error(errTip)
        }
        console.log('uploadError ' + errTip)
      }
      let key = function (up, file) {
        let date = getCurrentDate()
        let today = new Date()
        let time = today.getTime()
        let key = account + '/km/' + date + '/' + time + '/' + uuid.v1() + file.name
        return key
      }
      let filters = {
        mime_types: [
          {title: 'Image files', extensions: 'jpg,gif,png,jpeg'}
        ]
      }
      this.m7uploaders.push(
        uploadTo7moorlogoImgDomain(this.$store.state.session.user._id, 'uploadWXCustomerLogo', filters, fileAdded, beforeUploadSysLogo, upProgressSysLogo, upCompleteSysLogo, systemLogouploaded, error, key)
      )
    }
  },
  beforeDestroy () {
    this.m7uploaders.forEach(uploader => {
      uploader &&
      uploader.destroy &&
      uploader.destroy()
    })
  },
  mounted () {
    this.$nextTick(() => {
      this.initUpload()
    })
  },
  beforeMount () {
    if (this.data.open_kfid) {
      this.form = deepClone(this.data)
      this.oldData = deepClone(this.data)
    }
  }
}
</script>
<style lang="stylus" scope>
@import "../../../../../assets/common.styl"
.update_wxkf_customer
  width 460px
  margin 10px auto 0
  *
    font-size 12px
  .uploadBtn
    margin 6px 0 0 0
    min-width 90px
    height 24px
    line-height 24px
    cursor pointer
    color $c-main
    text-align left
    width 40px
  .icon_grey
    display inline-block
    width 60px
    height 60px
    border 1px solid #7f7f7f
    background #f2f2f2
  .wrap_logo
    text-align left
    height 64px
  .delete_btn
    color #fff
    background $c-pink
  .desc
    margin-top 4px
    color $c-prompt
    text-align left
  .welcomeTip
    cursor pointer
    display inline-block
    text-align center
    line-height 16px
    margin-left 2px
    position absolute
    top 12px
    right -36px
    font-size 10px
    color $c-main
</style>